import tkinter as tk
from tkinter import Toplevel, Entry, Button, Label, messagebox
from datetime import datetime

def priority_task(window, listbox, task_information_dict):
    # 获取当前选中的任务索引
    selected_index = listbox.curselection()
    if not selected_index:
        messagebox.showwarning("Warning", "Please select a task to edit.")
        return
    
    # 获取选中的任务字符串
    selected_task_str = listbox.get(selected_index)
    
    # 解析任务字符串
    task_parts = selected_task_str.split(' priority:')
    task_name = task_parts[0]
    task_priority_str = task_parts[1].split(' due to ')[0]
    task_due_date = task_parts[1].split(' due to ')[1]

    # 找到对应的任务信息
    for key, value in task_information_dict.items():
        if value['task_name'] == task_name and value['task_priority'] == task_priority_str and value['task_due_date'] == task_due_date:
            task_key = key
            break
    else:
        messagebox.showerror("Error", "Task not found in the dictionary.")
        return

    # 创建编辑窗口
    edit_window = Toplevel(window)
    edit_window.title("Edit Task Priority")

    # 标题输入框
    Label(edit_window, text="Title:").grid(row=0, column=0, padx=5, pady=5)
    title_entry = Entry(edit_window)
    title_entry.grid(row=0, column=1, padx=5, pady=5)
    title_entry.insert(0, value['task_name'])

    # 截止日期输入框
    Label(edit_window, text="Due Date (YYYY-MM-DD HH:MM:SS):").grid(row=1, column=0, padx=5, pady=5)
    due_date_entry = Entry(edit_window)
    due_date_entry.grid(row=1, column=1, padx=5, pady=5)
    due_date_entry.insert(0, value['task_due_date'])

    # 优先级下拉菜单
    Label(edit_window, text="Priority:").grid(row=2, column=0, padx=5, pady=5)
    priority_var = tk.StringVar(value=value['task_priority'])
    priority_options = ['high', 'medium', 'low']
    priority_menu = tk.OptionMenu(edit_window, priority_var, *priority_options)
    priority_menu.grid(row=2, column=1, padx=5, pady=5)

    # 保存按钮
    def save_task():
        new_task_name = title_entry.get()
        new_task_due_date = due_date_entry.get()
        new_task_priority = priority_var.get()

        if not new_task_name or not new_task_due_date or not new_task_priority:
            messagebox.showwarning("Input Error", "All fields are required.")
            return

        try:
            due_date = datetime.strptime(new_task_due_date, '%Y-%m-%d %H:%M:%S')
        except ValueError:
            messagebox.showwarning("Input Error", "Invalid date format. Please use YYYY-MM-DD HH:MM:SS.")
            return

        # 更新任务信息
        task_information_dict[task_key]['task_name'] = new_task_name
        task_information_dict[task_key]['task_priority'] = new_task_priority
        task_information_dict[task_key]['task_due_date'] = new_task_due_date

        # 更新 Listbox 显示
        listbox.delete(selected_index)
        listbox.insert(selected_index, f"{new_task_name} priority:{new_task_priority} due to {new_task_due_date}")

        # 保存更新后的任务信息到 JSON 文件
        from logic.json_function import save_json
        save_json('information/task_information.json', task_information_dict)

        # 关闭编辑窗口
        edit_window.destroy()

    save_button = Button(edit_window, text="Save", command=save_task)
    save_button.grid(row=3, column=0, columnspan=2, pady=10)

    # 取消按钮
    cancel_button = Button(edit_window, text="Cancel", command=edit_window.destroy)
    cancel_button.grid(row=4, column=0, columnspan=2, pady=5)

if __name__ == "__main__":
    # 这部分代码仅用于测试，实际使用时应从主窗口调用
    root = tk.Tk()
    listbox_task = tk.Listbox(root)
    listbox_task.pack()
    task_information_dict = {
        '1': {'task_name': 'Task 1', 'task_priority': 'high', 'task_due_date': '2024-10-30 12:00:00'},
        '2': {'task_name': 'Task 2', 'task_priority': 'medium', 'task_due_date': '2024-11-01 15:00:00'}
    }
    for each_task in task_information_dict.values():
        listbox_task.insert(tk.END, f"{each_task['task_name']} priority:{each_task['task_priority']} due to {each_task['task_due_date']}")
    
    button_task_edit = tk.Button(root, text='Edit Task Priority', command=lambda: priority_task(root, listbox_task, task_information_dict))
    button_task_edit.pack()
    
    root.mainloop()